<?php
/**
 * @author GhostWei
 * @date 2012-08015
 */
class resource_friendsite_concept extends system_concept_abstract {
	
	public function __construct($lang) {
		parent::__construct(array('lang' => $lang), array('lang = ?' => $lang));
	}
	
	public function init() {
		$this->setModel('resource_friendsite_model', 'friendsite');
		$this->setJoinLeftModel('resource_link_model', 'link.key = friendsite.link', 'link');
		$this->setModelCols('friendsite', array('id', 'lang', 'link', 'name', 'logo'));
		$this->setModelCols('friendsite', array('display_order', 'is_active', 'description', 'creationtime'));
		$this->setModelCols('link', array('key', 'url', 'click'));
	}
	
	public function save($row) {
		$row->set('name', trim($row->get('name')));
		if(strlen($row->getName()) < 2 || strlen($row->getName()) > 50) {
			throw new resource_exception("Site name length must be between 2~50 characters.");
		}
		if(!preg_match('/^[a-z0-9\-_]{5}$/is', $row->getLang())) {
			throw new resource_exception("Language formation error.");
		}
		if(!preg_match('/^(http|https|ftp)\:\/\/[a-zA-Z0-9]{1,}\.[a-zA-Z0-9\-\.]{1,}(.*)$/is', $row->getUrl())) {
			throw new resource_exception("SITE URL formation error.");
		}
		$row->setIsActive(($row->get('is_active') ? 1 : 0));
		
		$key = system_encrypt::shortUrl($row->getUrl());
		$row->setLink($key);
		$row->setKey($key);
		
		if($row->getId()) {
			if($this->fetch(array('id != ?' => $row->getId(), 'link = ?' => $key))) {
				throw new resource_exception("This Site is already Existing.");
			}
			$this->getModel('friendsite')->update($row->getModelData('friendsite'), array('id = ?' => $row->getId()));
		} else {
			if($this->fetch(array('link = ?' => $key))) {
				throw new resource_exception("This Site is already Existing.");
			}
			$row->setCreationtime(system_date::timestamp());
			$id = $this->getModel('friendsite')->insert($row->getModelData('friendsite'));
			$row->setId($id);
		}
		if(!$this->getModel('link')->fetchRow(array('`key` = ?' => $key))) {
			$row->setClick(0);
			$this->getModel('link')->insert($row->getModelData('link'));
		}
		return $row;
	}
	
	/**
	 * @return resource_display
	 */
	public function getLogo($row) {
		return new resource_display($row->get('logo'));
	}

}
